package com.cyzz.bookstore.modules.web;


import com.baomidou.mybatisplus.plugins.Page;
import com.cyzz.bookstore.common.base.MyBaseController;
import com.cyzz.bookstore.common.json.OrderFormVO;
import com.cyzz.bookstore.common.kd.KdApiOrderDemo;
import com.cyzz.bookstore.common.kd.OrderForKD;
import com.cyzz.bookstore.common.kd.UserForKD;
import com.cyzz.bookstore.common.myException.DBException;
import com.cyzz.bookstore.common.utils.DateUtils;
import com.cyzz.bookstore.modules.model.Book;
import com.cyzz.bookstore.modules.model.OrderForm;
import com.cyzz.bookstore.modules.model.User;
import com.cyzz.bookstore.modules.service.IBookService;
import com.cyzz.bookstore.modules.service.ICartService;
import com.cyzz.bookstore.modules.service.IOrderFormService;
import com.cyzz.bookstore.modules.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author CBY
 * @since 2018-05-30
 */
@Controller
@RequestMapping("/orderForm")
public class OrderFormController extends MyBaseController {
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private IBookService bookService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IUserService userService;

    /**
     * 确认订单（立即购买）
     * @param form
     * @return
     */
    @RequestMapping(value = "/confirmOrder", method = RequestMethod.POST)
    @ResponseBody
    public Object buyInstant(@RequestBody OrderFormVO.GetOrderForm form){
        //1.保存到订单表
        OrderForm orderForm = new OrderForm();
        orderForm.setOrderNumber(new Date().getTime());
        orderForm.setClientId(form.getUserid());
        orderForm.setStoreId(bookService.selectBookById(form.getBookid()).getBookstoreId());
        orderForm.setBookId(form.getBookid());
//        OrderFormVO orderFormVO = new OrderFormVO();
//        orderForm.setPurchaseDate(orderFormVO.changeToDate());//调用方法出错，注意修改再使用，空指针异常
        orderForm.setPurchaseDate(new Date(form.getDate()));
        orderForm.setPurchaseCount(form.getNumber());
        orderForm.setPrice(bookService.selectBookById(form.getBookid()).getPrice());
        orderForm.setIsDeal(0);
        orderFormService.insert(orderForm);
        //2.跟新图书的销售量
        Book book = bookService.selectBookById(form.getBookid());
        book.setSalesVolume(book.getSalesVolume()+form.getNumber());
        try {
            bookService.updataBook(book);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError();
        }
        return renderSuccess(null);
    }

    /**
     * 处理订单
     * @param orderNumber
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/dealOrder", method = RequestMethod.GET)
    @ResponseBody
    public Object dealOrder(@RequestParam("orderNumber") Long  orderNumber) throws Exception {
        OrderForm o = orderFormService.selectById(orderNumber);
        o.setIsDeal(1);
        orderFormService.updataOrderForm(o);

        KdApiOrderDemo demo =new KdApiOrderDemo();
        UserForKD sender =new UserForKD();
        UserForKD receiver=new UserForKD();
        OrderForKD order1=new OrderForKD();

        OrderForm orderForm = orderFormService.selectById(orderNumber);
        Book book = bookService.selectBookById(orderForm.getBookId());
        User store = userService.selectUserById(orderForm.getStoreId());
        User client = userService.selectUserById(orderForm.getClientId());

        order1.OrderCode= ""+orderNumber;
        order1.GoodsName=book.getTitle();
        order1.Remark="小心轻放";

        sender.Name=store.getUserName();
        sender.Mobile=store.getTelephone();
        sender.ProvinceName=store.getAddress();
        sender.CityName=store.getAddress();
        sender.ExpAreaName="青浦区";
        sender.Address="明珠路73号";

        receiver.Name=client.getUserName();
        receiver.Mobile=client.getTelephone();
        receiver.ProvinceName=client.getAddress();
        receiver.CityName= client.getAddress();
        receiver.ExpAreaName="天河区";
        receiver.Address="华南农业大学华山区";

        String url = demo.sendData(order1,sender,receiver);

        return renderSuccess(url);
    }

    /**
     * 获取顾客的订单消息（已购商品）
     * @param userid
     * @return
     */
    @RequestMapping(value = "/bought", method = RequestMethod.GET)
    @ResponseBody
    public Object getClientOrderMess( @RequestParam("userid") Long userid) {

        List<OrderForm> o = orderFormService.selectOrderFormByClientId(userid);
//        List<OrderFormVO.GetBoughtMess> orders = new ArrayList<>();
        OrderFormVO.GetBoughtMess boughtMess = new OrderFormVO.GetBoughtMess();
        for(OrderForm order:o){

            OrderFormVO.Orders or = new OrderFormVO.Orders();
            or.setId(order.getBookId());
            or.setTitle(bookService.selectBookById(order.getBookId()).getTitle());//找书名
            or.setPrice(order.getPrice());
            or.setNumber(order.getPurchaseCount());
            or.setBookStore(userService.selectUserById(order.getStoreId()).getUserName());//找店铺名
            boughtMess.addOrder(or);
        }
        return renderSuccess(boughtMess);
    }

    /**
     * 获取店铺的订单信息
     * @param userid
     * @return
     */
    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    @ResponseBody
    public Object getStoreOrderMess( @RequestParam("userid") Long userid) {
        List<OrderForm> o = orderFormService.selectOrderFormByStoreId(userid);//店铺id
        List<OrderFormVO.OrderMess> orders = new ArrayList<>();
        System.out.println(userid+" "+orders.size());
        for(OrderForm order:o){
            OrderFormVO.OrderMess orderMess = new OrderFormVO.OrderMess();
            OrderFormVO.bookMess bookMess = new OrderFormVO.bookMess();
            bookMess.setNum(order.getPurchaseCount());
            bookMess.setTitle(bookService.selectBookById(order.getBookId()).getTitle());//获得书名
            orderMess.setOrderNumber(order.getOrderNumber());
            orderMess.setClient(userService.selectUserById(order.getClientId()).getUserName());
            orderMess.setDate(DateUtils.date2String(order.getPurchaseDate()));
            orderMess.setIsDeal(order.getIsDeal());
            orderMess.setBooks(bookMess);
            orders.add(orderMess);//没有加入列表
        }
        return renderSuccess(orders);
    }
}
